import axios, { AxiosRequestConfig, Canceler, Axios, AxiosInterceptorManager, AxiosResponse, InternalAxiosRequestConfig } from 'axios'
import { message } from './func'

interface Config extends AxiosRequestConfig {
	cancel?: Canceler
}

export type AxiosPromiseNew<T = any> = Promise<T>

interface AxiosInstanceNew extends Axios {
	interceptors: {
		request: AxiosInterceptorManager<InternalAxiosRequestConfig>
		response: AxiosInterceptorManager<AxiosResponse>
	}
	(config: Config): AxiosPromiseNew
	(url: string, config?: AxiosRequestConfig): AxiosPromiseNew
}

// 基础配置
const requestConfig: Config = {
	baseURL: import.meta.env.VITE_BASEURL,
	timeout: 1000 * 60 * 5 //超时时间设置为5分钟
}

const request: AxiosInstanceNew = axios.create(requestConfig)

// 请求拦截器
request.interceptors.request.use(
	(req: any) => {
		return req
	},
	error => {
		return Promise.reject(error)
	}
)

// 返回拦截器
request.interceptors.response.use(
	(response: AxiosResponse) => {
		const data = response.data
		if (data) {
			if (data.code === 0) {
				return data
			} else {
				message(data.msg)
				return Promise.reject(data.msg)
			}
		} else {
			message('接口请求错误!')
			return Promise.reject('接口请求错误')
		}
	},
	error => {
		console.error('error:', '-------', error.response)
		return Promise.reject('服务器异常')
	}
)

export default request
